// =======================================================================
// 
//       Filename:  pluginmanager.cpp
// 
//    Description:  
// 
//        Version:  1.0
//        Created:  09.05.2010 00:17:37
//       Revision:  none
//       Compiler:  g++
// 
//         Author:  Dominik 'domachine' Burgdörfer (-), dominik.burgdoerfer@googlemail.com
//        Company:  -
// 
// =======================================================================

#include "pluginmanager.hpp"
#include "plugin.hpp"
#include "exceptions/pluginerror.hpp"
#include <boost/foreach.hpp>
#include <stdexcept>
#define foreach BOOST_FOREACH

using namespace boost;
using namespace std;

namespace fs = filesystem;

using webplodder::exceptions::Exception;
using webplodder::exceptions::PluginError;

namespace webplodder {
    PluginManager::PluginManager(const fs::path& pluginPath)
        : m_pluginPath(pluginPath)
    {
        
    }

    void PluginManager::scanPlugins() {
        fs::directory_iterator endIter;

        if(!fs::is_directory(m_pluginPath)) {
            throw Exception("unable to scan plugins");
        }

        fs::directory_iterator dIter(m_pluginPath);

        Plugin* plugin;
        for(; dIter != endIter; ++dIter) {
            if(dIter->path().extension() == ".so") {
                plugin = new Plugin(dIter->path());
                plugin->open();
                m_plugins.push_back(shared_ptr<Plugin>(plugin));
            }
        }
    }

    shared_ptr<Plugin> PluginManager::getPlugin(const string& name) {
        foreach(shared_ptr<Plugin> plugin, m_plugins) {
            
            if(plugin->name() == name)
                return plugin;
        }
        

        throw PluginError("no such plugin");
    }
}
